package object;

import java.io.*;


/**
 * This class is to describe a table of Tokens which are the result of lexical analysis.
 * You need to call method 'end' to stop writing to files when you meet the end of the source text
 * @author YaoXiao
 * @version 0.0
 * @date 18/09/2013
 */
public class TokenTable {
	private File outputFile;
	private FileWriter fileWriter;
	private String outputFileName = "";
	private ErrorReporter errorReporter = new ErrorReporter();
	/**
	 * Construct method
	 * @param outputFileName the name of the output file
	 * @throws Exception 
	 */
	public TokenTable(String outputFileName) throws Exception {
		String tableTitle = "TokenName\tAttributeValue\r\n";
		try {
			this.outputFileName = outputFileName;
			outputFile = new File( outputFileName );
			if( outputFile.exists()==true ){
				outputFile.delete();
			}
			outputFile.createNewFile();			
			fileWriter = new FileWriter(outputFile);
			fileWriter.write(tableTitle);			
		} catch (FileNotFoundException e) {
			throw new FileNotFoundException(outputFileName);
		} catch (IOException e) {
			errorReporter.reportFileWriteError(outputFileName, tableTitle);
		}
	}
	/**
	 * put Token into output File
	 * @param token
	 * @throws Exception
	 */
	public void put(Token token){
		try {
			fileWriter.write(token.toString());
		} catch (IOException e) {
			errorReporter.reportFileWriteError(outputFileName, token.toString());
		}
	}
	public void end() throws IOException{
		Token t = new Token("ENDFILE", "");
		try {
			fileWriter.write( t.toString());	
		} catch (IOException e) {
			errorReporter.reportFileWriteError(outputFileName, t.toString());			
		}finally{
			fileWriter.flush();
			fileWriter.close();
		}
	}

}
